#include <dateTimePack.h>
#define DATE_TIME_PACK_WAY 1

typedef struct
{
    uint64_t tmStamp;
    uint64_t tmSys;
    uint8_t tmUtc;
    pthread_mutex_t tmLock;
} tmSdDealStc;// time stamp and date deal struct

static tmSdDealStc tmStmpDateVal = {0, 0, 8, PTHREAD_MUTEX_INITIALIZER};


int timeSdInit()
{
#if DATE_TIME_PACK_WAY == 1
    pthread_mutex_lock(&tmStmpDateVal.tmLock);
    struct timeval tmpDateTm;
    gettimeofday(&tmpDateTm, NULL);
    tmStmpDateVal.tmStamp = tmpDateTm.tv_sec;

    struct timespec tmpsysTm;
    clock_gettime(CLOCK_MONOTONIC, &tmpsysTm);
    tmStmpDateVal.tmSys = tmpsysTm.tv_sec;
    pthread_mutex_unlock(&tmStmpDateVal.tmLock);
    return 1;
#else
#endif
}

int timeSdSetUtc(uint8_t setUtc)
{
    tmStmpDateVal.tmUtc = setUtc;
    return 1;
}

int timeSdSetStamp(uint64_t setTmStamp)
{
#if DATE_TIME_PACK_WAY == 1
    struct timeval tmptm = {0};
    tmptm.tv_sec = setTmStamp;
    settimeofday(&tmptm, NULL);
    system("hwclock -w -f /dev/rtc1");
    timeSdInit();
    return 1;
#else
#endif
}

int timeSdSetDate(timeDateNanoStc *setTmDate)
{
    timeSdSetStamp(date2stamp(&setTmDate->dateval));
    return 1;
}

uint64_t timeSdGetStamp()
{
#if DATE_TIME_PACK_WAY == 1
    uint64_t tmpstamp;
    struct timespec tmpsysTm;
    clock_gettime(CLOCK_MONOTONIC, &tmpsysTm);
    pthread_mutex_lock(&tmStmpDateVal.tmLock);
    tmpstamp = tmStmpDateVal.tmStamp + tmpsysTm.tv_sec - tmStmpDateVal.tmSys;
    pthread_mutex_unlock(&tmStmpDateVal.tmLock);
    return tmpstamp;
#else
#endif
}

timeDateNanoStc tmSdGetDate()
{
    timeDateNanoStc tmpdt;
    uint64_t tmpstmp = timeSdGetStamp();
    tmpdt.dateval = stamp2date(tmpstmp, tmStmpDateVal.tmUtc);
    struct timespec tmpsysTm;
    clock_gettime(CLOCK_MONOTONIC, &tmpsysTm);
    tmpdt.nanosec = tmpsysTm.tv_nsec;
    return tmpdt;
}

